from typing import Any

from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError


class DocImageAltProvider(ToolProvider):
    
    def _validate_credentials(self, credentials: dict[str, Any]) -> None:
        """
        验证提供的 Access Token 是否有效。
        """
        base_url = credentials.get("base_url")
        access_token = credentials.get("access_token")
        if not access_token:
            raise ToolProviderCredentialValidationError("Access Token 不能为空。")

        try:
            from openai import OpenAI
            from openai import AuthenticationError, APIConnectionError, OpenAIError
            # 尝试执行一个需要凭证的简单操作来验证
            client = OpenAI(
                base_url=base_url,
                api_key=access_token,
            )
            client.models.list()  # GiteeAI不校验Token
            # print("✅ access_token 和 base_url 验证成功！")
        except AuthenticationError as e:
            raise ToolProviderCredentialValidationError(f"认证失败 API Key 无效或缺失: {e}")
        except APIConnectionError as e:
            raise ToolProviderCredentialValidationError(f"连接失败，无法连接到 {base_url}: {e}")
        except OpenAIError as e:
            raise ToolProviderCredentialValidationError(f"OpenAI API 错误: {e}")
        except Exception as e:
            raise ToolProviderCredentialValidationError(f"验证失败: {e}")

    #########################################################################################
    # If OAuth is supported, uncomment the following functions.
    # Warning: please make sure that the sdk version is 0.4.2 or higher.
    #########################################################################################
    # def _oauth_get_authorization_url(self, redirect_uri: str, system_credentials: Mapping[str, Any]) -> str:
    #     """
    #     Generate the authorization URL for doc_image_alt OAuth.
    #     """
    #     try:
    #         """
    #         IMPLEMENT YOUR AUTHORIZATION URL GENERATION HERE
    #         """
    #     except Exception as e:
    #         raise ToolProviderOAuthError(str(e))
    #     return ""
        
    # def _oauth_get_credentials(
    #     self, redirect_uri: str, system_credentials: Mapping[str, Any], request: Request
    # ) -> Mapping[str, Any]:
    #     """
    #     Exchange code for access_token.
    #     """
    #     try:
    #         """
    #         IMPLEMENT YOUR CREDENTIALS EXCHANGE HERE
    #         """
    #     except Exception as e:
    #         raise ToolProviderOAuthError(str(e))
    #     return dict()

    # def _oauth_refresh_credentials(
    #     self, redirect_uri: str, system_credentials: Mapping[str, Any], credentials: Mapping[str, Any]
    # ) -> OAuthCredentials:
    #     """
    #     Refresh the credentials
    #     """
    #     return OAuthCredentials(credentials=credentials, expires_at=-1)
